package com.zhuliwei.controller;

import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.entity.ChatContent;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.exception.SystemException;
import com.zhuliwei.utils.IPUtil;
import com.zhuliwei.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.ai.audio.transcription.AudioTranscriptionPrompt;
import org.springframework.ai.audio.transcription.AudioTranscriptionResponse;
import org.springframework.ai.openai.OpenAiAudioTranscriptionModel;
import org.springframework.ai.openai.OpenAiAudioTranscriptionOptions;
import org.springframework.ai.openai.api.OpenAiAudioApi;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import static com.zhuliwei.constants.RabbitConstants.CHAT_EXCHANGE_NAME;

/**
 * @author 朱力维
 * @time 2024/11/25 15:07
 **/
@RestController
public class AudioUploadController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OpenAiAudioTranscriptionModel openAiAudioTranscriptionModel;

    // 语音转文字
    @PostMapping("/audioToText")
    public ResponseResult audioToText(MultipartFile audio, HttpServletRequest request) {
        try {
            OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder()
                    .withResponseFormat(OpenAiAudioApi.TranscriptResponseFormat.TEXT)
                    .withTemperature(0f)
                    .build();
//        FileSystemResource audioFile = new FileSystemResource("C:\\Users\\49915\\Desktop\\后端Demo\\spring-ai-demo\\1732429823942.mp3");
            MultipartFile multipartFile = audio;
            FileSystemResource audioFile = convert(multipartFile);
            AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);
            AudioTranscriptionResponse response = openAiAudioTranscriptionModel.call(transcriptionRequest);
            String result = response.getResult().getOutput();
            asyncInsert("语音转文字，文件名：" + audioFile.getFilename(), request, result, 0, SystemConstants.CHAT_CONTENT_TRANSLATION);
            return ResponseResult.okResult(result);
        } catch (Exception e) {
            asyncInsert("语音转文字", request, "语音转文字出现异常", 1, SystemConstants.CHAT_CONTENT_TRANSLATION);
            e.printStackTrace();
            throw new SystemException(AppHttpCodeEnum.AUDIO_UPLOAD_ERR);
        }
    }

    public static FileSystemResource convert(MultipartFile multipartFile) throws IOException {
        // 创建一个临时文件
        File tempFile = File.createTempFile("temp", multipartFile.getOriginalFilename());

        // 将 MultipartFile 写入临时文件
        multipartFile.transferTo(tempFile);

        // 将临时文件转化为 FileSystemResource
        return new FileSystemResource(tempFile);
    }

    /**
     * 提问记录异步存入数据库
     *
     * @param userInput 提问内容
     * @param request
     * @param answer    回答内容
     */
    private void asyncInsert(String userInput, HttpServletRequest request, String answer, Integer status, String type) {
        ChatContent chatContent = new ChatContent();
        chatContent.setType(type);
        chatContent.setIpAddress(IPUtil.getIpAddress(request));
        chatContent.setQuestion(userInput);
        chatContent.setAnswer(answer);
        chatContent.setCreateBy(SecurityUtils.getUserId());
        chatContent.setCreateTime(new Date());
        chatContent.setStatus(status);
        rabbitTemplate.convertAndSend(CHAT_EXCHANGE_NAME, "", chatContent);
    }
}
